package com.cms.controller.admin;

import java.util.Date;
import java.util.HashMap;

import org.apache.commons.lang.ArrayUtils;

import com.cms.Feedback;
import com.cms.entity.Coupon;
import com.cms.entity.Order;
import com.cms.entity.Product;
import com.cms.entity.ProductCategory;
import com.cms.routes.RouteMapping;

@RouteMapping(url = "/admin/coupon")
public class CouponController extends BaseController {
	
	public void productCategorySet(){
		setAttr("productCategoryTree", new ProductCategory().dao().findTree());
		render(getView("coupon/productCategorySet"));
	}
	
	public void productSet(){
		Integer pageNumber = getParaToInt("pageNumber");
        if (pageNumber == null) {
            pageNumber = 1;
        }
        String name = getPara("name");
        Long productCategoryId = getParaToLong("productCategoryId");
        setAttr("page", new Product().dao().findPage(pageNumber, PAGE_SIZE, productCategoryId,name,null,null));
        setAttr("name", name);
		render(getView("coupon/productSet"));
	}
	
	/**
	 * 添加
	 */
	public void add() {
		render(getView("coupon/add"));
	}

	/**
	 * 保存
	 */
	public void save() {
		Coupon coupon = getModel(Coupon.class,"",true); 
		coupon.setCreateDate(new Date());
		coupon.setModifyDate(new Date());
		coupon.save();
		redirect(getListQuery("/admin/coupon/list"));
	}

	/**
	 * 编辑
	 */
	public void edit() {
		Long id = getParaToLong("id");
		setAttr("coupon", new Coupon().dao().findById(id));
		render(getView("coupon/edit"));
	}

	/**
	 * 更新
	 */
	public void update() {
		Coupon coupon = getModel(Coupon.class,"",true); 
		coupon.setModifyDate(new Date());
		coupon.update();
		redirect(getListQuery("/admin/coupon/list"));
	}
	
	/**
	 * 列表
	 */
	public void list() {
	    String name = getPara("name");
		Integer pageNumber = getParaToInt("pageNumber");
		if(pageNumber==null){
			pageNumber = 1;
		}
		setAttr("page", new Coupon().dao().findPage(name,pageNumber,PAGE_SIZE));
		setAttr("name", name);
		render(getView("coupon/list"));
	}
	
	public void useList(){
		Integer pageNumber = getParaToInt("pageNumber");
		if(pageNumber==null){
			pageNumber = 1;
		}
		Long couponId = getParaToLong("couponId");
		Coupon coupon = new Coupon().findById(couponId);
		setAttr("coupon", coupon);
		setAttr("page", new Order().dao().findCouponPage(couponId,pageNumber,PAGE_SIZE));
		render(getView("coupon/useList"));
	}

	/**
	 * 删除
	 */
	public void delete() {
		Long ids[] = getParaValuesToLong("ids");
		if(ArrayUtils.isNotEmpty(ids)){
			for(Long id:ids){
				new Coupon().dao().deleteById(id);
			}
		}
		renderJson(Feedback.success(new HashMap<>()));
	}
}
